package com.tedu.weibo.common.exception;

import com.tedu.weibo.common.result.JsonResult;
import com.tedu.weibo.common.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

//@ControllerAdvice
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
//    @ResponseBody
    public JsonResult doHandleRuntimeException(RuntimeException e) {
        System.out.println("处理RuntimeException");
        log.error(e.getMessage(), e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e) {
        System.out.println("处理IllegalArgumentException");
        log.error(e.getMessage(), e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String message = e.getFieldError().getDefaultMessage();
        System.out.println("message:"+e.getFieldError().getDefaultMessage());
        log.error(message,e);
        return new JsonResult(StatusCode.VALIDATE_EARRO,message);
    }
    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage();
        message = message.substring(message.indexOf(":")+1).trim();
        log.error(message, e);
        return new JsonResult(StatusCode.VALIDATE_EARRO,message);
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable e) {
        log.error(e.getMessage(), e);
        return new JsonResult(StatusCode.UNKNOWN_EARRO);
    }
}
